package com.lyf.boot.modules.payment;

import com.alipay.api.domain.AlipayTradePagePayModel;
import com.ijpay.alipay.AliPayApi;
import com.ijpay.alipay.AliPayApiConfig;
import com.ijpay.alipay.AliPayApiConfigKit;
import com.lyf.boot.controller.AbstractAliPayApiController;
import com.lyf.boot.properties.AliPayProperties;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 支付宝支付
 * @author Luyufan
 * @date 2023/8/22 10:23
 */
@Slf4j
@Controller
@RequiredArgsConstructor
@RequestMapping("/aliPay")
public class AlipayController extends AbstractAliPayApiController {

    private final AliPayProperties alipayProperties;

    @Override
    public AliPayApiConfig getApiConfig() {
        AliPayApiConfig aliPayApiConfig;
        try {
            aliPayApiConfig = AliPayApiConfigKit.getApiConfig(alipayProperties.getAppId());
        } catch (Exception e) {
            aliPayApiConfig = AliPayApiConfig.builder()
                    .setAppId(alipayProperties.getAppId())
                    .setAliPayPublicKey(alipayProperties.getPublicKey())
                    .setCharset("UTF-8")
                    .setPrivateKey(alipayProperties.getPrivateKey())
                    .setServiceUrl(alipayProperties.getServerUrl())
                    .setSignType("RSA2")
                    .build();
        }
        return aliPayApiConfig;
    }

    /**
     * 支付宝支付
     * @param response
     */
    @RequestMapping("/pcPay")
    @ResponseBody
    public void pcPay(HttpServletResponse response){
        try {
            String totalAmount = "100.00";
            String outTradeNo = "123456789";
            String returnUrl = alipayProperties.getDomain() + "/";
            String notifyUrl = alipayProperties.getDomain() + "/";
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();
            model.setOutTradeNo(outTradeNo);
            model.setProductCode("FAST_INSTANT_TRADE_PAY");
            model.setTotalAmount(totalAmount);
            model.setSubject("Java PC支付测试");
            model.setBody("Java IJPay PC支付测试");
            model.setPassbackParams("passback_params");
            AliPayApi.tradePage(response, model, notifyUrl, returnUrl);
        } catch (Exception e) {
            log.error("支付失败", e);
        }
    }


}
